#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
趋势预测系统 - 第七步执行模块
基于历史数据和技术指标预测未来1个月走势
"""

import sys
import os
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
import warnings
warnings.filterwarnings('ignore')

sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from real_data_fetcher import RealDataFetcher
from simple_prediction_model import SimplePredictionModel

class TrendPredictionSystem:
    """趋势预测系统"""
    
    def __init__(self):
        self.data_fetcher = RealDataFetcher()
        self.prediction_model = SimplePredictionModel()
        
        # 预测参数配置
        self.prediction_config = {
            'prediction_days': 30,      # 预测30天（约1个月）
            'confidence_level': 0.8,    # 80%置信度
            'trend_threshold': 0.05,    # 5%的趋势判断阈值
        }
        
    def print_header(self, title):
        """打印标题"""
        print(f"\n{'='*80}")
        print(f"🔮 {title}")
        print(f"{'='*80}")
        
    def predict_single_stock(self, stock_info):
        """预测单只股票的未来走势"""
        stock_code = stock_info.get('code')
        stock_name = stock_info.get('name', '')
        
        try:
            # 获取历史数据用于预测
            historical_data = self.data_fetcher.get_stock_data(stock_code, 200)
            if historical_data is None or historical_data.empty:
                print(f"无法获取 {stock_code} 的历史数据")
                return None
                
            # 使用预测模型
            prediction_result = self.prediction_model.predict_price(historical_data)
            
            if prediction_result:
                current_price = historical_data['close'].iloc[-1]
                
                # 计算趋势概率
                trend_probs = self.calculate_trend_probabilities(historical_data, prediction_result)
                
                # 计算价格区间
                target_price = prediction_result.get('predicted_price', current_price)
                confidence = self.prediction_config['confidence_level']
                
                price_range = self.calculate_price_range(current_price, target_price, confidence)
                
                # 生成技术信号
                technical_signals = self.analyze_technical_signals(historical_data)
                
                # 投资建议
                investment_advice = self.generate_investment_advice(
                    trend_probs['upward_probability'], 
                    current_price, 
                    target_price
                )
                
                result = {
                    'code': stock_code,
                    'name': stock_name,
                    'current_price': current_price,
                    'target_price': target_price,
                    'price_change_pct': (target_price - current_price) / current_price * 100,
                    'upward_probability': trend_probs['upward_probability'],
                    'downward_probability': trend_probs['downward_probability'],
                    'sideways_probability': trend_probs['sideways_probability'],
                    'price_range': price_range,
                    'technical_signals': technical_signals,
                    'investment_advice': investment_advice,
                    'risk_level': self.assess_risk_level(trend_probs, current_price, target_price),
                    'prediction_data': prediction_result
                }
                
                return result
                
            else:
                print(f"预测模型执行失败: {stock_code}")
                return None
                
        except Exception as e:
            print(f"预测 {stock_code} 失败: {e}")
            return None
            
    def calculate_trend_probabilities(self, historical_data, prediction_result):
        """计算趋势概率"""
        try:
            close_prices = historical_data['close']
            
            # 基于技术指标计算概率
            ma5 = close_prices.rolling(5).mean().iloc[-1]
            ma20 = close_prices.rolling(20).mean().iloc[-1]
            current_price = close_prices.iloc[-1]
            
            # 基础概率
            base_prob = 50
            
            # 均线信号调整
            if current_price > ma5 > ma20:
                base_prob += 20
            elif current_price < ma5 < ma20:
                base_prob -= 20
                
            # 价格动量调整
            price_change = (current_price - close_prices.iloc[-5]) / close_prices.iloc[-5] * 100
            if price_change > 2:
                base_prob += 10
            elif price_change < -2:
                base_prob -= 10
                
            # 限制在合理范围内
            upward_prob = max(0, min(100, base_prob))
            downward_prob = 100 - upward_prob
            sideways_prob = 0
            
            return {
                'upward_probability': upward_prob,
                'downward_probability': downward_prob,
                'sideways_probability': sideways_prob
            }
        except:
            return {'upward_probability': 50, 'downward_probability': 50, 'sideways_probability': 0}
            
    def calculate_price_range(self, current_price, target_price, confidence):
        """计算价格预测区间"""
        try:
            # 基于历史波动率计算价格区间
            price_change = target_price - current_price
            volatility_factor = 1.96 if confidence == 0.95 else 1.28  # 95%或80%置信度
            
            # 估算波动率（简化计算）
            estimated_volatility = abs(price_change) * 0.5
            
            upper_bound = target_price + estimated_volatility * volatility_factor
            lower_bound = target_price - estimated_volatility * volatility_factor
            
            return {
                'upper_bound': max(upper_bound, current_price * 0.8),
                'lower_bound': max(lower_bound, current_price * 0.5),
                'target_price': target_price
            }
        except:
            return {
                'upper_bound': current_price * 1.2,
                'lower_bound': current_price * 0.8,
                'target_price': current_price
            }
            
    def analyze_technical_signals(self, historical_data):
        """生成技术信号"""
        try:
            close_prices = historical_data['close']
            signals = {}
            
            # 移动平均线信号
            ma5 = close_prices.rolling(5).mean()
            ma20 = close_prices.rolling(20).mean()
            
            current_price = close_prices.iloc[-1]
            signals['ma_signal'] = 0
            
            # MA信号评分
            if current_price > ma5.iloc[-1] > ma20.iloc[-1]:
                signals['ma_signal'] = 1  # 上涨信号
            elif current_price < ma5.iloc[-1] < ma20.iloc[-1]:
                signals['ma_signal'] = -1  # 下跌信号
                
            # MACD信号
            ema12 = close_prices.ewm(span=12).mean()
            ema26 = close_prices.ewm(span=26).mean()
            macd_line = ema12 - ema26
            signal_line = macd_line.ewm(span=9).mean()
            
            macd_current = macd_line.iloc[-1]
            signal_current = signal_line.iloc[-1]
            
            if macd_current > signal_current and macd_current > 0:
                signals['macd_signal'] = 1
            elif macd_current < signal_current and macd_current < 0:
                signals['macd_signal'] = -1
            else:
                signals['macd_signal'] = 0
                
            # RSI信号
            delta = close_prices.diff()
            gain = (delta.where(delta > 0, 0)).rolling(window=14).mean()
            loss = (-delta.where(delta < 0, 0)).rolling(window=14).mean()
            rs = gain / loss
            rsi = 100 - (100 / (1 + rs))
            
            rsi_current = rsi.iloc[-1]
            if rsi_current > 70:
                signals['rsi_signal'] = -1  # 超买
            elif rsi_current < 30:
                signals['rsi_signal'] = 1   # 超卖
            else:
                signals['rsi_signal'] = 0
                
            # 成交量信号
            volume = historical_data['volume']
            volume_ma = volume.rolling(20).mean()
            
            recent_volume = volume.iloc[-5:].mean()
            avg_volume = volume_ma.iloc[-1]
            
            if recent_volume > avg_volume * 1.5:
                signals['volume_signal'] = 1  # 放量
            elif recent_volume < avg_volume * 0.5:
                signals['volume_signal'] = -1  # 缩量
            else:
                signals['volume_signal'] = 0
                
            return signals
            
        except Exception as e:
            print(f"计算技术信号失败: {e}")
            return {}
            
    def generate_investment_advice(self, upward_prob, current_price, target_price):
        """生成投资建议"""
        try:
            price_change = (target_price - current_price) / current_price * 100
            
            if upward_prob >= 70:
                return "适量买入"
            elif upward_prob >= 60:
                return "谨慎买入"
            elif upward_prob >= 40:
                return "观望为主"
            else:
                return "建议回避"
        except:
            return "建议观望"
            
    def assess_risk_level(self, trend_probs, current_price, target_price):
        """评估风险等级"""
        try:
            upward_prob = trend_probs.get('upward_probability', 0)
            price_volatility = abs(target_price - current_price) / current_price * 100
            
            if upward_prob >= 70 and price_volatility < 10:
                return "低风险"
            elif upward_prob >= 50 and price_volatility < 15:
                return "中等风险"
            elif upward_prob >= 40:
                return "较高风险"
            else:
                return "高风险"
        except:
            return "风险未知"

    def load_deep_analysis_results(self, filename="deep_analysis_results.csv"):
        """加载深度分析结果"""
        try:
            df = pd.read_csv(filename)
            return df.to_dict('records')
        except Exception as e:
            print(f"加载深度分析结果失败: {e}")
            # 如果CSV不存在，从最终排序结果中获取Top 3
            try:
                df = pd.read_csv("final_investment_ranking.csv")
                return df.head(3).to_dict('records')
            except:
                return []
                
    def get_prediction_data(self, stock_code, days=200):
        """获取用于预测的历史数据"""
        try:
            data = self.data_fetcher.get_stock_data(stock_code, days)
            if data is not None and not data.empty:
                return data
            return None
        except Exception as e:
            print(f"获取 {stock_code} 预测数据失败: {e}")
            return None
            
    def calculate_technical_signals(self, stock_data):
        """计算技术指标信号"""
        try:
            close_prices = stock_data['close']
            signals = {}
            
            # 移动平均线信号
            ma5 = close_prices.rolling(5).mean()
            ma20 = close_prices.rolling(20).mean()
            ma60 = close_prices.rolling(60).mean()
            
            current_price = close_prices.iloc[-1]
            signals['ma_signal'] = 0
            
            # MA信号评分
            if current_price > ma5.iloc[-1] > ma20.iloc[-1] > ma60.iloc[-1]:
                signals['ma_signal'] = 2  # 强烈上涨信号
            elif current_price > ma5.iloc[-1] > ma20.iloc[-1]:
                signals['ma_signal'] = 1  # 上涨信号
            elif current_price < ma5.iloc[-1] < ma20.iloc[-1] < ma60.iloc[-1]:
                signals['ma_signal'] = -2  # 强烈下跌信号
            elif current_price < ma5.iloc[-1] < ma20.iloc[-1]:
                signals['ma_signal'] = -1  # 下跌信号
                
            # MACD信号
            ema12 = close_prices.ewm(span=12).mean()
            ema26 = close_prices.ewm(span=26).mean()
            macd_line = ema12 - ema26
            signal_line = macd_line.ewm(span=9).mean()
            
            macd_current = macd_line.iloc[-1]
            signal_current = signal_line.iloc[-1]
            
            if macd_current > signal_current and macd_current > 0:
                signals['macd_signal'] = 1
            elif macd_current < signal_current and macd_current < 0:
                signals['macd_signal'] = -1
            else:
                signals['macd_signal'] = 0
                
            # RSI信号
            delta = close_prices.diff()
            gain = (delta.where(delta > 0, 0)).rolling(window=14).mean()
            loss = (-delta.where(delta < 0, 0)).rolling(window=14).mean()
            rs = gain / loss
            rsi = 100 - (100 / (1 + rs))
            
            rsi_current = rsi.iloc[-1]
            if rsi_current > 70:
                signals['rsi_signal'] = -1  # 超买
            elif rsi_current < 30:
                signals['rsi_signal'] = 1   # 超卖
            else:
                signals['rsi_signal'] = 0
                
            # 成交量信号
            volume = stock_data['volume']
            volume_ma = volume.rolling(20).mean()
            
            recent_volume = volume.iloc[-5:].mean()
            avg_volume = volume_ma.iloc[-1]
            
            if recent_volume > avg_volume * 1.5:
                signals['volume_signal'] = 1  # 放量
            elif recent_volume < avg_volume * 0.5:
                signals['volume_signal'] = -1  # 缩量
            else:
                signals['volume_signal'] = 0
                
            return signals
            
        except Exception as e:
            print(f"计算技术信号失败: {e}")
            return {}
            
    def predict_price_trend(self, stock_data, stock_info):
        """预测价格趋势"""
        try:
            close_prices = stock_data['close']
            current_price = close_prices.iloc[-1]
            
            # 获取技术信号
            signals = self.calculate_technical_signals(stock_data)
            
            # 使用简单预测模型
            prediction_result = self.prediction_model.predict_price(stock_data, stock_info.get('code', ''))
            
            # 基于多种因子的综合预测
            prediction_factors = {
                'technical_score': stock_info.get('technical_score', 50),
                'fundamental_score': stock_info.get('fundamental_score', 50),
                'trend_signals': signals,
                'current_price_position': self.calculate_price_position(stock_data),
                'momentum': self.calculate_momentum(stock_data)
            }
            
            # 计算预测概率
            trend_probability = self.calculate_trend_probability(prediction_factors)
            
            # 预测价格区间
            price_forecast = self.generate_price_forecast(
                current_price, 
                trend_probability, 
                stock_data
            )
            
            return {
                'current_price': current_price,
                'prediction_result': prediction_result,
                'trend_probability': trend_probability,
                'price_forecast': price_forecast,
                'technical_signals': signals,
                'prediction_factors': prediction_factors
            }
            
        except Exception as e:
            print(f"预测价格趋势失败: {e}")
            return {}
            
    def calculate_price_position(self, stock_data):
        """计算当前价格在历史区间中的位置"""
        try:
            close_prices = stock_data['close']
            current_price = close_prices.iloc[-1]
            
            recent_high = close_prices.rolling(60).max().iloc[-1]
            recent_low = close_prices.rolling(60).min().iloc[-1]
            
            position = ((current_price - recent_low) / (recent_high - recent_low) * 100 
                       if recent_high != recent_low else 50)
            
            return position
        except:
            return 50
            
    def calculate_momentum(self, stock_data):
        """计算价格动量"""
        try:
            close_prices = stock_data['close']
            
            # 不同周期的涨跌幅
            momentum_1w = (close_prices.iloc[-1] / close_prices.iloc[-5] - 1) * 100
            momentum_2w = (close_prices.iloc[-1] / close_prices.iloc[-10] - 1) * 100
            momentum_1m = (close_prices.iloc[-1] / close_prices.iloc[-20] - 1) * 100
            
            return {
                '1_week': momentum_1w,
                '2_week': momentum_2w,
                '1_month': momentum_1m
            }
        except:
            return {'1_week': 0, '2_week': 0, '1_month': 0}
            
    def calculate_trend_probability(self, prediction_factors):
        """计算趋势概率"""
        try:
            upward_score = 0
            downward_score = 0
            
            # 技术面评分影响
            tech_score = prediction_factors.get('technical_score', 50)
            if tech_score > 70:
                upward_score += 20
            elif tech_score > 60:
                upward_score += 10
            elif tech_score < 40:
                downward_score += 10
            elif tech_score < 30:
                downward_score += 20
                
            # 基本面评分影响
            fund_score = prediction_factors.get('fundamental_score', 50)
            if fund_score > 70:
                upward_score += 15
            elif fund_score > 60:
                upward_score += 8
            elif fund_score < 40:
                downward_score += 8
            elif fund_score < 30:
                downward_score += 15
                
            # 技术信号影响
            signals = prediction_factors.get('trend_signals', {})
            ma_signal = signals.get('ma_signal', 0)
            macd_signal = signals.get('macd_signal', 0)
            rsi_signal = signals.get('rsi_signal', 0)
            
            signal_score = ma_signal * 10 + macd_signal * 8 + rsi_signal * 5
            if signal_score > 0:
                upward_score += signal_score
            else:
                downward_score += abs(signal_score)
                
            # 价格位置影响
            price_position = prediction_factors.get('current_price_position', 50)
            if price_position > 80:
                downward_score += 15  # 高位风险
            elif price_position < 20:
                upward_score += 15    # 低位机会
                
            # 动量影响
            momentum = prediction_factors.get('momentum', {})
            recent_momentum = momentum.get('1_week', 0)
            if recent_momentum > 5:
                upward_score += 10
            elif recent_momentum < -5:
                downward_score += 10
                
            # 计算最终概率
            total_score = upward_score + downward_score
            if total_score == 0:
                return {'upward': 50, 'downward': 50, 'sideways': 0}
                
            upward_prob = upward_score / total_score * 100
            downward_prob = downward_score / total_score * 100
            
            # 如果上涨下跌概率都不明显，增加横盘概率
            if abs(upward_prob - downward_prob) < 20:
                sideways_prob = 20
                upward_prob = (upward_prob * 0.8)
                downward_prob = (downward_prob * 0.8)
            else:
                sideways_prob = 0
                
            return {
                'upward': round(upward_prob, 1),
                'downward': round(downward_prob, 1),
                'sideways': round(sideways_prob, 1)
            }
            
        except Exception as e:
            print(f"计算趋势概率失败: {e}")
            return {'upward': 33, 'downward': 33, 'sideways': 34}
            
    def generate_price_forecast(self, current_price, trend_probability, stock_data):
        """生成价格预测区间"""
        try:
            # 计算历史波动率
            close_prices = stock_data['close']
            returns = close_prices.pct_change().dropna()
            volatility = returns.std()
            
            # 预测期间的预期涨跌幅
            upward_prob = trend_probability.get('upward', 33) / 100
            downward_prob = trend_probability.get('downward', 33) / 100
            
            # 基于概率的预期收益
            expected_return = (upward_prob * 0.08 - downward_prob * 0.06)  # 假设上涨8%，下跌6%
            
            # 考虑波动性的价格区间
            volatility_adjustment = volatility * np.sqrt(30)  # 30天波动
            
            # 预测价格区间
            target_price = current_price * (1 + expected_return)
            upper_bound = target_price * (1 + volatility_adjustment * 1.5)
            lower_bound = target_price * (1 - volatility_adjustment * 1.5)
            
            # 涨跌幅计算
            target_change = (target_price - current_price) / current_price * 100
            upper_change = (upper_bound - current_price) / current_price * 100
            lower_change = (lower_bound - current_price) / current_price * 100
            
            return {
                'target_price': round(target_price, 2),
                'upper_bound': round(upper_bound, 2),
                'lower_bound': round(lower_bound, 2),
                'target_change_pct': round(target_change, 1),
                'upper_change_pct': round(upper_change, 1),
                'lower_change_pct': round(lower_change, 1),
                'confidence_level': self.prediction_config['confidence_level']
            }
            
        except Exception as e:
            print(f"生成价格预测失败: {e}")
            return {}
            
    def predict_single_stock(self, stock_info):
        """预测单只股票"""
        stock_code = stock_info['code']
        stock_name = stock_info['name']
        
        print(f"\n🔮 趋势预测: {stock_code} {stock_name}")
        print("-" * 70)
        
        # 获取预测数据
        stock_data = self.get_prediction_data(stock_code, 200)
        if stock_data is None:
            print(f"   ❌ 无法获取预测数据")
            return None
            
        print(f"   ✅ 基于 {len(stock_data)} 天历史数据进行预测")
        
        # 执行趋势预测
        prediction = self.predict_price_trend(stock_data, stock_info)
        if not prediction:
            print(f"   ❌ 预测执行失败")
            return None
            
        current_price = prediction.get('current_price', 0)
        trend_prob = prediction.get('trend_probability', {})
        price_forecast = prediction.get('price_forecast', {})
        signals = prediction.get('technical_signals', {})
        
        print(f"   💰 当前价格: {current_price:.2f}元")
        
        # 显示趋势概率
        print(f"\n   📊 未来1个月趋势概率:")
        print(f"      • 上涨概率: {trend_prob.get('upward', 0):.1f}%")
        print(f"      • 下跌概率: {trend_prob.get('downward', 0):.1f}%")
        print(f"      • 震荡概率: {trend_prob.get('sideways', 0):.1f}%")
        
        # 显示价格预测
        if price_forecast:
            print(f"\n   🎯 价格预测区间 (置信度{price_forecast.get('confidence_level', 0.8)*100:.0f}%):")
            print(f"      • 目标价格: {price_forecast.get('target_price', 0):.2f}元 "
                  f"({price_forecast.get('target_change_pct', 0):+.1f}%)")
            print(f"      • 上限价格: {price_forecast.get('upper_bound', 0):.2f}元 "
                  f"({price_forecast.get('upper_change_pct', 0):+.1f}%)")
            print(f"      • 下限价格: {price_forecast.get('lower_bound', 0):.2f}元 "
                  f"({price_forecast.get('lower_change_pct', 0):+.1f}%)")
                  
        # 显示技术信号
        print(f"\n   📈 技术信号分析:")
        ma_signal = signals.get('ma_signal', 0)
        macd_signal = signals.get('macd_signal', 0)
        rsi_signal = signals.get('rsi_signal', 0)
        volume_signal = signals.get('volume_signal', 0)
        
        signal_desc = {
            2: "强烈看涨", 1: "看涨", 0: "中性", -1: "看跌", -2: "强烈看跌"
        }
        
        print(f"      • 均线信号: {signal_desc.get(ma_signal, '中性')}")
        print(f"      • MACD信号: {signal_desc.get(macd_signal, '中性')}")
        print(f"      • RSI信号: {signal_desc.get(rsi_signal, '中性')}")
        print(f"      • 成交量信号: {signal_desc.get(volume_signal, '中性')}")
        
        # 投资建议
        upward_prob = trend_prob.get('upward', 33)
        target_change = price_forecast.get('target_change_pct', 0)
        
        if upward_prob > 60 and target_change > 5:
            recommendation = "积极买入"
            risk_level = "中等风险"
        elif upward_prob > 50 and target_change > 0:
            recommendation = "适量买入"
            risk_level = "中等风险"
        elif upward_prob < 40 or target_change < -5:
            recommendation = "建议回避"
            risk_level = "较高风险"
        else:
            recommendation = "观望为主"
            risk_level = "中等风险"
            
        print(f"\n   💡 投资建议: {recommendation}")
        print(f"   ⚠️ 风险等级: {risk_level}")
        
        # 操作建议
        price_position = prediction.get('prediction_factors', {}).get('current_price_position', 50)
        
        if price_position > 80:
            operation = "当前位置偏高，建议等待回调"
        elif price_position < 20:
            operation = "当前位置偏低，可考虑分批建仓"
        else:
            operation = "当前位置适中，可适量配置"
            
        print(f"   🎯 操作建议: {operation}")
        
        # 返回预测结果
        result = {
            **stock_info,
            'prediction_data': {
                'current_price': current_price,
                'trend_probability': trend_prob,
                'price_forecast': price_forecast,
                'technical_signals': signals,
                'investment_recommendation': recommendation,
                'risk_level': risk_level,
                'operation_suggestion': operation,
                'prediction_date': datetime.now().strftime('%Y-%m-%d'),
                'forecast_period': '30天'
            }
        }
        
        return result
        
    def run_trend_prediction(self):
        """运行趋势预测系统"""
        self.print_header("第七步：趋势预测系统 - 未来1个月走势预测")
        
        # 加载深度分析结果
        deep_results = self.load_deep_analysis_results()
        if not deep_results:
            print("❌ 无法加载深度分析结果，请先执行第六步")
            return []
            
        print(f"📋 预测参数配置:")
        print(f"   • 预测期间: {self.prediction_config['prediction_days']} 天")
        print(f"   • 置信水平: {self.prediction_config['confidence_level']*100:.0f}%")
        print(f"   • 趋势阈值: {self.prediction_config['trend_threshold']*100:.0f}%")
        
        print(f"\n🔮 开始对Top 3股票进行趋势预测...")
        
        prediction_results = []
        
        for i, stock_info in enumerate(deep_results, 1):
            print(f"\n[{i}/{len(deep_results)}] 趋势预测进度")
            
            result = self.predict_single_stock(stock_info)
            if result:
                prediction_results.append(result)
                
        # 生成预测总结报告
        self.generate_prediction_report(prediction_results)
        
        return prediction_results
        
    def generate_prediction_report(self, prediction_results):
        """生成预测总结报告"""
        print(f"\n📊 趋势预测总结报告:")
        print(f"   • 预测股票数量: {len(prediction_results)}")
        
        if len(prediction_results) > 0:
            print(f"\n🎯 Top 3股票预测汇总:")
            print(f"{'股票':<15} {'当前价':<8} {'目标价':<8} {'涨跌幅':<8} {'上涨概率':<8} {'建议':<10}")
            print("-" * 75)
            
            for result in prediction_results:
                code_name = f"{result['code']} {result['name'][:4]}"
                pred_data = result.get('prediction_data', {})
                
                current_price = pred_data.get('current_price', 0)
                forecast = pred_data.get('price_forecast', {})
                target_price = forecast.get('target_price', 0)
                target_change = forecast.get('target_change_pct', 0)
                upward_prob = pred_data.get('trend_probability', {}).get('upward', 0)
                recommendation = pred_data.get('investment_recommendation', '观望')
                
                print(f"{code_name:<15} {current_price:<8.2f} {target_price:<8.2f} "
                      f"{target_change:<8.1f} {upward_prob:<8.1f} {recommendation:<10}")
                      
            print(f"\n💡 投资策略建议:")
            
            # 统计投资建议
            recommendations = {}
            for result in prediction_results:
                rec = result.get('prediction_data', {}).get('investment_recommendation', '观望')
                recommendations[rec] = recommendations.get(rec, 0) + 1
                
            for rec, count in recommendations.items():
                print(f"   • {rec}: {count} 只股票")
                
            # 风险提示
            print(f"\n⚠️ 预测风险提示:")
            print(f"   • 以上预测基于历史数据和技术分析，仅供参考")
            print(f"   • 股市波动受多种因素影响，预测存在不确定性")
            print(f"   • 建议结合市场环境和个人情况做出投资决策")
            print(f"   • 严格执行止盈止损，控制投资风险")
            
            # 月度操作建议
            buy_count = sum(1 for r in prediction_results 
                          if r.get('prediction_data', {}).get('investment_recommendation') in ['积极买入', '适量买入'])
            
            if buy_count >= 2:
                monthly_strategy = "市场机会较好，可适度增加仓位"
            elif buy_count == 1:
                monthly_strategy = "市场机会一般，保持适中仓位"
            else:
                monthly_strategy = "市场风险较大，建议降低仓位或观望"
                
            print(f"\n📅 未来1个月策略: {monthly_strategy}")
                
        else:
            print(f"   ⚠️ 没有完成趋势预测的股票")
            
    def save_prediction_results(self, prediction_results, filename="trend_prediction_results.csv"):
        """保存预测结果"""
        if prediction_results:
            save_data = []
            for result in prediction_results:
                pred_data = result.get('prediction_data', {})
                save_record = {
                    'code': result['code'],
                    'name': result['name'],
                    'current_price': pred_data.get('current_price', 0),
                    'target_price': pred_data.get('price_forecast', {}).get('target_price', 0),
                    'target_change_pct': pred_data.get('price_forecast', {}).get('target_change_pct', 0),
                    'upper_bound': pred_data.get('price_forecast', {}).get('upper_bound', 0),
                    'lower_bound': pred_data.get('price_forecast', {}).get('lower_bound', 0),
                    'upward_probability': pred_data.get('trend_probability', {}).get('upward', 0),
                    'downward_probability': pred_data.get('trend_probability', {}).get('downward', 0),
                    'sideways_probability': pred_data.get('trend_probability', {}).get('sideways', 0),
                    'investment_recommendation': pred_data.get('investment_recommendation', ''),
                    'risk_level': pred_data.get('risk_level', ''),
                    'operation_suggestion': pred_data.get('operation_suggestion', ''),
                    'prediction_date': pred_data.get('prediction_date', ''),
                    'forecast_period': pred_data.get('forecast_period', '')
                }
                save_data.append(save_record)
                
            df = pd.DataFrame(save_data)
            df.to_csv(filename, index=False, encoding='utf-8-sig')
            print(f"\n💾 趋势预测结果已保存到 {filename}")
            return filename
        return None

if __name__ == "__main__":
    # 创建趋势预测系统实例
    prediction_system = TrendPredictionSystem()
    
    # 执行趋势预测
    results = prediction_system.run_trend_prediction()
    
    # 保存结果
    prediction_system.save_prediction_results(results)
    
    print(f"\n🎉 第七步：趋势预测系统执行完成！")
    print(f"   • 成功预测了 {len(results)} 只股票的未来1个月走势")
    print(f"   • 提供了详细的价格目标和操作建议")
    print(f"   • 准备进入第八步：投资建议生成")
